<?php

namespace addon\lian\model\core\order;

use addon\lian\model\Config;
use addon\lian\model\sqlmodel\LianGoodsModel;
use addon\lian\model\sqlmodel\LianMemberModel;
use addon\lian\model\core\member\CoreLianLevelService;
use addon\lian\model\core\member\CoreLianMemberAttrService;
use addon\lian\model\sqlmodel\LianPubLineModel;
use addon\lian\model\sqlmodel\OrderGoodsModel;
use addon\lian\model\sqlmodel\MemberModel;
use app\dict\order\OrderGoodsDict;
use think\facade\Log;

class CoreLianRewardService
{

    public function handleReward($site_id, $order_data){
        Log::write('========ly_lian========handleReward====================order_data' . json_encode($order_data));
        $goods_ids = $this->getLianGoodsIds($site_id);
        $order_goods = (new OrderGoodsModel())->alias('og')
            ->where('og.site_id', $site_id)
            ->where('og.member_id', $order_data['member_id'])
            ->where('og.order_id', $order_data['order_id'])
            ->whereIn('og.goods_id', $goods_ids)
            ->join('order o', 'og.order_id = o.order_id', 'INNER')
            ->whereIn('o.order_status',  [OrderGoodsDict::wait_delivery, OrderGoodsDict::delivery, OrderGoodsDict::delivery_finish])
            ->findOrEmpty();
        Log::write('========ly_lian========handleReward===========order_goods:'.json_encode($order_goods));
        $order_member = (new MemberModel())->where('site_id', $site_id)->where('member_id', $order_data['member_id'])->findOrEmpty();

        if(!$order_goods){
            Log::write('========ly_lian========handleReward===========订单中没有联营商品，直接返回。');
            return false;
        } 

        // 需要增加判断该会员的当前订单是否是复购订单，如果是复购订单，则要进行复购见单奖
        $order_goods_count = (new OrderGoodsModel())->alias('og')
            ->where('og.site_id', $site_id)
            ->where('og.member_id', $order_data['member_id'])
            ->whereIn('og.goods_id', $goods_ids)
            ->join('order o', 'og.order_id = o.order_id', 'INNER')
            ->whereIn('o.order_status',  [OrderGoodsDict::wait_delivery, OrderGoodsDict::delivery, OrderGoodsDict::delivery_finish])
            ->count();

        // if($order_goods){
        //     $this->recommendReward($site_id, $order_goods, $order_data);
        //     $this->seeReward($site_id, $order_goods, $order_data);
        //     // $this->equalReward($site_id, $order_goods, $order_data);
        // }

        if($order_goods){
            $this->recommendReward($site_id, $order_goods, $order_data);
            if($order_goods_count > 1){
                $this->fuseeReward($site_id, $order_goods, $order_data, $order_goods_count);
            }
            $this->seeReward($site_id, $order_goods, $order_data);
        }

        
    }


    public function recommendReward($site_id, $order_goods, $order_data){
        try{
            Log::write('============ly_lian===========recommendReward===========');
            $member = (new CoreLianMemberAttrService())->getParentMember($site_id, $order_goods['member_id']);
            $parent = (new LianMemberModel())->where('site_id', $site_id)->where('member_id', $member['pid'])->findOrEmpty();

            $level = (new CoreLianLevelService())->getLevelByMember($site_id, $parent);
            $config = (new Config())->getLianBasicsConfig($site_id);
            $config = $config['data']['value'];

            $thaw_status = $config['first_reward_frozen'];
            $reward_thaw_status = (new CoreLianRewardAttrService())->getThawStatus($site_id);

            $reward_set = (new CoreLianRewardAttrService())->getGoodsRewardSet($site_id, $order_goods, $level);//获取商品的奖励设置。
            $lian_goods = (new LianGoodsModel())->where('site_id', $site_id)->where('goods_id', $order_goods['goods_id'])->findOrEmpty();//获取商品的奖励设置。
            
            $reward = 0; // 初始化奖励金额
            if(!$parent->isEmpty()){
                $price = (new CoreLianRewardAttrService())->getCountType($site_id, $order_goods, $order_data);
                Log::write('============ly_lian===========recommendReward===========price' . $price);

                if($lian_goods['is_rule'] == 1){
                    if($level['recommend_rate'] != 0){
                        $reward = $price * $level['recommend_rate'] / 100;
                    }elseif($level['recommend_money'] != 0){
                        $reward = $level['recommend_money'];
                    }

                }elseif($lian_goods['is_rule'] == 2){
                    if($reward_set['recommend_rate'] != 0){
                        $reward = $price * $reward_set['recommend_rate'] / 100; 
                    }elseif($reward_set['recommend_money'] != 0){
                        $reward = $reward_set['recommend_money']; 
                    }
                }

                if($parent['thaw_status'] == 0){//如果会员的冻结收益已解冻，则不再冻结直推奖励
                    if($thaw_status == 1 && $level['level_num'] == 2){//只有老板身份的直推奖才冻结
                        $frozen = $price * $level['frozen_rate'] / 100; 
                        // $reward = $reward - $frozen; 
                    }else{
                        $frozen = 0; // 冻结金额。
                    }
                }else{
                    $frozen = 0; 
                }
                
                if($reward > 0){ // 奖励金额大于0，才进行奖励。
                    $take_type = (new CoreLianRewardAttrService())->getTakeType($site_id);

                    (new CoreLianRewardAttrService())->addLianReward($site_id, $parent['member_id'], $parent['level_id'], $order_goods['order_id'], 
                        $order_goods['member_id'], $config['settle_cycle'], $price, $level['recommend_rate'], $reward, 0, $reward_thaw_status, $level['frozen_rate'], $frozen);
                    
                    // 更新会员的收益金额。
                    (new CoreLianMemberAttrService())->incReward($site_id, $parent['member_id'], $reward);
                    // 更新会员的冻结金额。
                    (new CoreLianMemberAttrService())->incFrozenReward($site_id, $parent['member_id'], $frozen);

                    // if($level['level_num'] == 2){//只有老板身份的，他的上级才能获得平级奖
                    //     $this->equalReward($site_id, $parent, $reward, $order_goods);
                    // }
                }
            }else{
                Log::write('============ly_lian===========recommendReward===========会员没有上级，不发放直推奖');
            }
        }catch(\Exception $e){
            Log::write('=ly_lian===recommendReward===error:' . $e->getMessage() . '===line:' . $e->getLine() . '===file:' . $e->getFile());
        }
    }

    //见点奖
    public function seeReward($site_id, $order_goods, $order_data){
        Log::write('============ly_lian===========seeReward===========');
        $order_member = (new LianMemberModel())->where('site_id', $site_id)->where('member_id', $order_data['member_id'])->findOrEmpty();

        $lian_parent = (new LianMemberModel())->where('site_id', $site_id)->where('member_id', $order_member['lian_pid'])->findOrEmpty();
        $lian_parent_level = (new CoreLianLevelService())->getLevelByMember($site_id, $lian_parent);

        $parent = (new LianMemberModel())->where('site_id', $site_id)->where('member_id', $order_member['lian_pid'])->findOrEmpty();
        $parent_level = (new CoreLianLevelService())->getLevelByMember($site_id, $parent);

        // if($parent->isEmpty() || $order_member['pid'] == 0) return;
        // if($parent['status'] == 1) return; //上级会员已冻结，则不再发放见点奖

        // if($parent_level['level_num'] == 2){
        //     $reward_member = $parent;
        // }else{
        //     if($lian_parent['status'] == 1){
        //         Log::write('---see---上级会员已冻结，则不再发放见点奖');
        //         return; //上级会员已冻结，则不再发放见点奖
        //     } 
        //     if($lian_parent->isEmpty() || $order_member['lian_pid'] == 0){
        //         Log::write('---see---上级会员不存在，则不再发放见点奖');
        //         return;
        //     } 
        //     if($lian_parent['lian_pid'] > 0){    
        //         $reward_member = (new LianMember())->where('site_id', $site_id)->where('member_id', $lian_parent['lian_pid'])->findOrEmpty();
        //     }else{
        //         return;
        //     }
        // }


        if($parent['lian_pid'] == 0){
            $reward_member = (new LianMemberModel())->where('site_id', $site_id)->where('member_id', $parent['member_id'])->findOrEmpty();
        }else{
            $reward_member = (new LianMemberModel())->where('site_id', $site_id)->where('member_id', $parent['lian_pid'])->findOrEmpty();
        }
        
        $see_time = strtotime($reward_member['up_time']);
        Log::write('---see---升级时间：' . $see_time . '---' . '--订单支付时间：' .   $order_goods['pay_time'] . '---see_member:' . json_encode($reward_member));
        if($see_time >= $order_goods['pay_time']){
            Log::write('---see---升级时间大于订单支付时间，不发放见点奖');
            return;  //升级的同时不发放见点奖
        } 

        $reward_thaw_status = (new CoreLianRewardAttrService())->getSeeThawStatus($site_id, $reward_member);
        Log::write('---see---reward_thaw_status:' . $reward_thaw_status);

        $level = (new CoreLianLevelService())->getLevelByMember($site_id, $reward_member);
        $config = (new Config())->getLianBasicsConfig($site_id);
        $config = $config['data']['value'];

        $reward_set = (new CoreLianRewardAttrService())->getGoodsRewardSet($site_id, $order_goods, $level);
        $lian_goods = (new LianGoodsModel())->where('site_id', $site_id)->where('goods_id', $order_goods['goods_id'])->findOrEmpty();

        if(!$reward_member->isEmpty() && $level['level_num'] == 2){//只有老板身份的才获得见点奖
            Log::write('---see---见点奖---');
            $price = (new CoreLianRewardAttrService())->getCountType($site_id, $order_goods, $order_data);

            if($lian_goods['is_rule'] == 1){
                if($level['see_rate'] != 0){
                    $reward = $price * $level['see_rate'] / 100;
                }elseif($level['see_money'] != 0){
                    $reward = $level['see_money'];
                }
            }elseif($lian_goods['is_rule'] == 2){
                
                if($reward_set['see_rate'] != 0){
                    $reward = $price * $reward_set['see_rate'] / 100; 
                }elseif($reward_set['see_money'] != 0){
                    $reward = $reward_set['see_money']; 
                }
            }
           
            // //见点奖冻结
            if($reward_member['thaw_status'] == 0){
                if($level['see_frozen'] == 1){      
                    // $frozen = $price * $level['frozen_rate'] / 100;
                    $frozen = $reward * $level['frozen_rate'] / 100;  //见点奖冻结金额 = 奖励金额 * 冻结比例
                    // $reward = $reward - $frozen; 
                }else{
                    $frozen = 0; 
                }
            }else{
                $frozen = 0;  
            }
                
            if($reward > 0){
                (new CoreLianRewardAttrService())->addLianReward($site_id, $reward_member['member_id'], $reward_member['level_id'], $order_goods['order_id'], 
                $order_goods['member_id'], $config['settle_cycle'], $price, $level['see_rate'], $reward, 1, $reward_thaw_status, $level['frozen_rate'],$frozen);

                 // 更新会员的收益金额。
                (new CoreLianMemberAttrService())->incReward($site_id, $reward_member['member_id'], $reward); 
                 // 更新会员的冻结金额。
                (new CoreLianMemberAttrService())->incFrozenReward($site_id, $reward_member['member_id'], $frozen); //累加会员冻结金额

                //尝试平级奖
                $this->equalReward($site_id, $reward_member, $reward, $order_goods);
            }
        }
    }

    // 培育奖
    public function cultivateReward($site_id, $parent, $order_data){
        Log::write('============ly_lian===========cultivateReward======' );

        $level = (new CoreLianLevelService())->getLevelByMember($site_id, $parent);
        $config = (new Config())->getLianBasicsConfig($site_id);
        $config = $config['data']['value'];

        $order_goods = (new CoreLianRewardAttrService())->getOrderGoods($site_id, $order_data);
        $reward_set = (new CoreLianRewardAttrService())->getGoodsRewardSet($site_id, $order_goods, $level);

        $lian_goods = (new LianGoodsModel())->where('site_id', $site_id)->where('goods_id', $order_goods['goods_id'])->findOrEmpty();
        $reward_thaw_status = (new CoreLianRewardAttrService())->getCultivateThawStatus($site_id, $parent);

        if($level['level_num'] == 2){//只有老板身份的才获得培育奖
            $price = (new CoreLianRewardAttrService())->getCountType($site_id, $order_goods, $order_data);

            if($lian_goods['is_rule'] == 1){
                if(isset($level['cultivate_rate']) && $level['cultivate_rate'] != 0){
                    $reward = $price * $level['cultivate_rate'] / 100; 
                }elseif(isset($level['cultivate_money']) && $level['cultivate_money'] != 0){
                    $reward = $level['cultivate_money']; 
                }
            }elseif($lian_goods['is_rule'] == 2){
                if(isset($reward_set['cultivate_rate']) && $reward_set['cultivate_rate'] != 0){
                    $reward = $price * $reward_set['cultivate_rate'] / 100;
                }elseif(isset($reward_set['cultivate_money']) && $reward_set['cultivate_money'] != 0){
                    $reward = $reward_set['cultivate_money']; 
                }
            }
            
            //培育奖冻结
            if($parent['thaw_status'] == 0){
                if($level['cultivate_frozen'] == 1){      
                    // $frozen = $price * $level['frozen_rate'] / 100; // 计算冻结金额。
                    $frozen = $reward * $level['frozen_rate'] / 100; // 计算冻结金额。
                    // $reward = $reward - $frozen; // 减去冻结金额。
                }else{
                    $frozen = 0; 
                    // $reward = $reward - $frozen; 
                }
            }else{
                $frozen = 0;  
                // $reward = $reward - $frozen;  
            }
            

            if($reward > 0){
                (new CoreLianRewardAttrService())->addLianReward($site_id, $parent['member_id'], $level['level_id'], $order_data['order_id'], 
                $order_data['member_id'], $config['settle_cycle'], $price, $level['cultivate_rate'], $reward, 2, $reward_thaw_status, 
                $level['frozen_rate'],$frozen); 

                 // 更新会员的收益金额。
                (new CoreLianMemberAttrService())->incReward($site_id, $parent['member_id'], $reward);
                // 更新会员的冻结收益金额。
                (new CoreLianMemberAttrService())->incFrozenReward($site_id, $parent['member_id'], $frozen);

                 //尝试平级奖
                //  $this->equalReward($site_id, $parent, $reward, $order_data);
            }
        }  
    }

    // 平级奖
    public function equalReward($site_id, $parent, $reward, $order_data){
        Log::write('============ly_lian===========equalReward======' );
        if($parent['pid'] == 0){
            Log::write('====ly_lian===没有上级不发放平级奖');
            return;
        }

        $equal_member = (new LianMemberModel())->where('site_id', $site_id)->where('member_id', $parent['pid'])->findOrEmpty(); 
        $level = (new CoreLianLevelService())->getLevelByMember($site_id, $equal_member);
        $config = (new Config())->getLianBasicsConfig($site_id);
        $config = $config['data']['value'];
        
        $equal_time = strtotime($parent['up_time']);
        Log::write('---equal---升级时间：' . $equal_time . '---' . '--订单支付时间：' . $order_data['pay_time'] . '---equal_member_id' . $equal_member['member_id']);
        
        if($equal_time >= $order_data['pay_time']){
            Log::write('升级时间大于等于订单支付时间不发放平级奖');
            return; // 升级时间大于等于订单创建时间不发放平级奖。
        } 

        // if(!$equal_member->isEmpty() && $level['level_num'] == 2){//只有老板身份的才获得平级奖
        if($level['level_num'] == 2){//只有老板身份的才获得平级奖
            if($level['equal_rate'] != 0){
                $money = $reward * $level['equal_rate'] / 100;
            }elseif($level['equal_money'] != 0){
                $money = $level['equal_money']; 
            }

            if($money > 0){
                (new CoreLianRewardAttrService())->addLianReward($site_id, $equal_member['member_id'], $level['level_id'], $order_data['order_id'], 
                $order_data['member_id'], $config['settle_cycle'], $reward, $level['equal_rate'], $money, 3, 1, 0, 0);
            
                // 更新会员的收益金额。
                (new CoreLianMemberAttrService())->incReward($site_id, $equal_member['member_id'], $money);
            }
        }else{
            Log::write('---ly_lian---没有上级或者上级不是老板身份不发放平级奖');
            return;
        }
    }


    // 复购见单奖
    public function fuseeReward($site_id, $order_goods, $order_data, $order_goods_count){
        Log::write('============ly_lian===========fuseeReward======开始处理复购见单奖');
        
        try {
            // 获取配置信息
            $config = (new Config())->getLianBasicsConfig($site_id);
            $config = $config['data']['value'];
            
            // 获取当前下单会员信息
            $order_member = (new LianPubLineModel())->where('site_id', $site_id)
                ->where('member_id', $order_data['member_id'])->findOrEmpty();
                
            if ($order_member->isEmpty()) {
                Log::write('============ly_lian===========fuseeReward======订单会员不存在');
                return false;
            }
            
            // 获取当前会员的订单数量
            $goods_ids = $this->getLianGoodsIds($site_id);
            Log::write("============ly_lian===========fuseeReward======会员ID:{$order_data['member_id']}的订单数量:{$order_goods_count}");
            
            // 只有第2单及以上才触发复购见单奖
            if ($order_goods_count < 2) {
                Log::write('============ly_lian===========fuseeReward======订单数量小于2，不触发复购见单奖');
                return false;
            }
            
            // 获取商品配置
            $lian_goods = (new LianGoodsModel())->where('site_id', $site_id)
                ->where('goods_id', $order_goods['goods_id'])->findOrEmpty();
            
            // 从公排中查找上级，根据订单数量确定奖励层级
            $this->processPublineReward($site_id, $order_member, $order_goods_count, $order_goods, $order_data, $config, $lian_goods);
            
            Log::write('============ly_lian===========fuseeReward======复购见单奖处理完成');
            return true;
            
        } catch (\Exception $e) {
            Log::write('============ly_lian===========fuseeReward======处理异常: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 处理公排奖励分配
     */
    private function processPublineReward($site_id, $order_member, $order_goods_count, $order_goods, $order_data, $config, $lian_goods) {
        // 获取会员的公排路径
        $member_path = trim($order_member['path'], ',');
        if (empty($member_path)) {
            Log::write('============ly_lian===========fuseeReward======会员公排路径为空');
            return;
        }
        
        $path_array = explode(',', $member_path);
        $path_length = count($path_array);
        
        // 确定要奖励的层级：第几单就奖励第几层
        $target_level = $order_goods_count;
        
        Log::write("============ly_lian===========fuseeReward======第{$order_goods_count}单，要奖励第{$target_level}层上级");
        
        // 检查是否有足够的上级层数
        if ($target_level > $path_length) {
            Log::write("============ly_lian===========fuseeReward======没有第{$target_level}层上级，上级总数只有{$path_length}层");
            return;
        }
        
        // 从路径中获取对应层级的上级会员ID
        if ($target_level > 0 && isset($path_array[$path_length - $target_level])) {
            $target_member_id = $path_array[$path_length - $target_level];
            
            // 获取目标上级会员信息
            $target_member = (new LianMemberModel())->where('site_id', $site_id)
                ->where('member_id', $target_member_id)->findOrEmpty();
                
            if ($target_member->isEmpty()) {
                Log::write("============ly_lian===========fuseeReward======目标上级会员不存在，ID:{$target_member_id}");
                return;
            }
            
            // 检查上级是否有获得奖励的资格
            if ($this->checkRewardQualification($site_id, $target_member, $target_level)) {
                // 计算并发放奖励
                $this->calculateAndGiveReward($site_id, $target_member, $order_goods, $order_data, $config, $lian_goods, $target_level);
            }
        }
    }
    
    /**
     * 检查上级会员是否有获得奖励的资格
     */
    private function checkRewardQualification($site_id, $target_member, $target_level) {
        try {
            // 获取上级会员的订单数量
            $goods_ids = $this->getLianGoodsIds($site_id);
            $member_order_count = (new OrderGoodsModel())->alias('og')
                ->where('og.site_id', $site_id)
                ->where('og.member_id', $target_member['member_id'])
                ->whereIn('og.goods_id', $goods_ids)
                ->join('order o', 'og.order_id = o.order_id', 'INNER')
                ->whereIn('o.order_status', [OrderGoodsDict::wait_delivery, OrderGoodsDict::delivery, OrderGoodsDict::delivery_finish])
                ->count();
                
            Log::write("============ly_lian===========fuseeReward======检查资格：上级会员ID:{$target_member['member_id']}的订单数量:{$member_order_count}，需要层级:{$target_level}");
            
            // 上级的订单数量必须大于等于当前要奖励的层级数（即上级必须至少有相应数量的订单）
            $qualified = $member_order_count >= $target_level;
            
            if ($qualified) {
                Log::write("============ly_lian===========fuseeReward======上级会员符合获奖资格");
            } else {
                Log::write("============ly_lian===========fuseeReward======上级会员不符合获奖资格，订单数不足");
            }
            
            return $qualified;
            
        } catch (\Exception $e) {
            Log::write('============ly_lian===========fuseeReward======检查资格异常: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 计算并发放奖励
     */
    private function calculateAndGiveReward($site_id, $target_member, $order_goods, $order_data, $config, $lian_goods, $target_level) {
        try {
            // 获取上级等级信息
            $level = (new CoreLianLevelService())->getLevelByMember($site_id, $target_member);
            
            // 获取奖励配置
            $reward_set = (new CoreLianRewardAttrService())->getGoodsRewardSet($site_id, $order_goods, $level);
            $reward_thaw_status = (new CoreLianRewardAttrService())->getThawStatus($site_id);
            
            // 计算奖励金额
            $price = (new CoreLianRewardAttrService())->getCountType($site_id, $order_goods, $order_data);
            $reward = 0;
            
            // 根据商品规则计算奖励
            if ($lian_goods['is_rule'] == 1) {
                // 使用等级规则
                if (isset($level['fusee_rate']) && $level['fusee_rate'] != 0) {
                    $reward = $price * $level['fusee_rate'] / 100;
                } elseif (isset($level['fusee_money']) && $level['fusee_money'] != 0) {
                    $reward = $level['fusee_money'];
                }
            } elseif ($lian_goods['is_rule'] == 2) {
                // 使用商品规则
                if (isset($reward_set['fusee_rate']) && $reward_set['fusee_rate'] != 0) {
                    $reward = $price * $reward_set['fusee_rate'] / 100;
                } elseif (isset($reward_set['fusee_money']) && $reward_set['fusee_money'] != 0) {
                    $reward = $reward_set['fusee_money'];
                }
            }
            
            // 计算冻结金额
            $frozen = 0;
            if ($target_member['thaw_status'] == 0) {
                if (isset($level['fusee_frozen']) && $level['fusee_frozen'] == 1) {
                    $frozen = $reward * $level['frozen_rate'] / 100;
                }
            }
            
            Log::write("============ly_lian===========fuseeReward======计算奖励：价格:{$price}，奖励:{$reward}，冻结:{$frozen}");
            
            if ($reward > 0) {
                // 添加奖励记录，奖励类型设为4表示复购见单奖
                (new CoreLianRewardAttrService())->addLianReward(
                    $site_id, 
                    $target_member['member_id'], 
                    $target_member['level_id'], 
                    $order_goods['order_id'],
                    $order_goods['member_id'], 
                    $config['settle_cycle'], 
                    $price, 
                    isset($level['fusee_rate']) ? $level['fusee_rate'] : (isset($reward_set['fusee_rate']) ? $reward_set['fusee_rate'] : 0), 
                    $reward, 
                    4, // 奖励类型：4=复购见单奖
                    $reward_thaw_status, 
                    $level['frozen_rate'], 
                    $frozen
                );
                
                // 更新会员收益金额
                (new CoreLianMemberAttrService())->incReward($site_id, $target_member['member_id'], $reward);
                
                // 更新会员冻结金额
                (new CoreLianMemberAttrService())->incFrozenReward($site_id, $target_member['member_id'], $frozen);
                
                Log::write("============ly_lian===========fuseeReward======成功发放复购见单奖：会员ID:{$target_member['member_id']}，奖励金额:{$reward}");
            } else {
                Log::write("============ly_lian===========fuseeReward======奖励金额为0，不发放");
            }
            
        } catch (\Exception $e) {
            Log::write('============ly_lian===========fuseeReward======计算奖励异常: ' . $e->getMessage());
        }
    }


    public function getLianGoodsIds($site_id){
        return (new LianGoodsModel())->where('site_id', $site_id)->where('is_lian', 1)->column('goods_id');
    }
}